package com.flycent.hqhs.ui;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.lang.ref.WeakReference;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.annotation.view.ViewInject;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.flycent.hqhs.App;
import com.flycent.hqhs.Constants;
import com.flycent.hqhs.R;
import com.flycent.hqhs.UserBaseInfo;
import com.flycent.hqhs.bean.MyMessage;
import com.flycent.hqhs.bean.UserInfo;
import com.flycent.hqhs.http.WebClient;
import com.flycent.hqhs.http.WebException;
import com.flycent.hqhs.ui.view.BadgeView;
import com.flycent.hqhs.ui.view.SimpleTitleBar;
import com.flycent.hqhs.util.ContextUtil;
import com.flycent.hqhs.util.EnviromentUtil;
import com.flycent.hqhs.util.PreferenceUtil;
import com.flycent.hqhs.util.SdkVersionUtil;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 我的
 * @author fbl
 */
public class MineActivity extends SimpleTitleBarActivity{

	@ViewInject(id = R.id.mine_relat_order ,click = "butClick") RelativeLayout mOrderRelat;
	@ViewInject(id = R.id.mine_relat_coupon ,click = "butClick") RelativeLayout mCouponRelat;
	@ViewInject(id = R.id.mine_relat_attention ,click = "butClick") RelativeLayout mAttentionRelat;
	@ViewInject(id = R.id.mine_relat_browse_record ,click = "butClick") RelativeLayout mRecordRelat;
	@ViewInject(id = R.id.mine_relat_evaluate ,click = "butClick") RelativeLayout mEvaluateRelat;
	@ViewInject(id = R.id.mine_relat_note ,click = "butClick") RelativeLayout mNoteRelat;
	@ViewInject(id = R.id.mine_relat_account_manager ,click = "butClick") RelativeLayout mAccountManagerRelat;
	@ViewInject(id = R.id.login_or_register_but ,click = "butClick") Button mLoginOrRegisterBut;
	@ViewInject(id = R.id.user_to_login_head_relat ) RelativeLayout mToLoginHaedRelat;
	@ViewInject(id = R.id.user_login_head_relat ) RelativeLayout mLoginHaedRelat;
	@ViewInject(id = R.id.user_face_image ,click = "butClick" ) ImageView mUserFaceImg;
	@ViewInject(id = R.id.user_name_text ) TextView mUserNameText;
	@ViewInject(id = R.id.user_price_text ) TextView mUserBalanceText;
	@ViewInject(id = R.id.text6 ) TextView mMessageText;


	/* 请求码 */
	private static final int IMAGE_REQUEST_CODE = 0;
	private static final int CAMERA_REQUEST_CODE = 1;
	private static final int RESULT_REQUEST_CODE = 2;
	private boolean isLogin = false;
	private UserInfo mUserInfo;
	private BadgeView badge;
	private MyMessage myMessage;
	private MyHandler mHandler;


	//---------------------------------------------

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.activity_mine);
		FinalActivity.initInjectedView(this);
		//手机的android系统API版本
		int version = SdkVersionUtil.getAndroidSDKVersion();
		App.showLog("version===="+version);

		initBadge();

		mHandler = new MyHandler(this);
	}



	@Override
	protected void onResume() {
		super.onResume();

		JudgeLoginAsync();

	}

	@Override
	protected void onDestroy() {

		mHandler.removeCallbacksAndMessages(null);
		super.onDestroy();
		//FileUtil.clearFile(FileUtil.SDCARDPATH);// 清楚sd卡中保存的内容
	}


	//---------------------------------------------

	private void JudgeLoginAsync(){

		new Thread(){
			public void run() {
				try {
					WebClient.getInstance(MineActivity.this).checkLogin();
					mHandler.sendEmptyMessage(0);
				} catch (WebException e) {
					if( "shop.common.unauthorized".equals(e.getStatusCode()) ){
						mHandler.sendEmptyMessage(1);
					}else {
						Log.e(TAG, "Check the login fail, " + e.toString());
					}
				}catch (Exception e) {
					Log.e(TAG, "Check the login fail, " + e.toString());
				}
			};
		}.start();
	}


	//UI Event---------------------------------------

	public void butClick(View v){

		//选择头像
		if( v == mUserFaceImg ){
			new PopupWindows(MineActivity.this, mUserFaceImg);
		
		}

		//登录
		if( v == mLoginOrRegisterBut ){
			ContextUtil.startActivity(this, LoginActivity.class);
		}

		//我的订单
		if( v == mOrderRelat ){
			if( isLogin){
				ContextUtil.startActivity(this, OrderManagerActivity.class);
			}else {
				App.showShortToast(R.string.please_login_too);
			}
		}

		//优惠劵
		if( v == mCouponRelat ){
			if( isLogin){
				ContextUtil.startActivity(this, CouponActivity.class);
			}else {
				App.showShortToast(R.string.please_login_too);
			}

		}

		//我的关注
		if( v == mAttentionRelat ){
			if( isLogin){
				ContextUtil.startActivity(this, FollowActivity.class);
			}else {
				App.showShortToast(R.string.please_login_too);
			}

		}

		//浏览记录
		if( v == mRecordRelat ){
			if( isLogin){
				ContextUtil.startActivity(this, BrowsingHistoryActivity.class);
			}else {
				App.showShortToast(R.string.please_login_too);
			}
		}

		//评价晒单
		if( v == mEvaluateRelat ){
			if( isLogin){
				ContextUtil.startActivity(this, EvaluationOrSunSingleActivity.class);
			}else {
				App.showShortToast(R.string.please_login_too);
			}
		}

		//我的消息
		if( v == mNoteRelat ){
			if( isLogin){
				ContextUtil.startActivity(this, MessageManagementActivity.class);
			}else {
				App.showShortToast(R.string.please_login_too);
			}
			//resetBadge();
		}

		//账户管理
		if( v == mAccountManagerRelat ){
			if(isLogin){
				ContextUtil.startActivity(this, AccountManagementActivity.class);
			}else {
				App.showShortToast(R.string.please_login_too);
			}

		}

	}

	private int getUnreadMessage(){

		int num = 0;
		if(myMessage == null ){
			return num;
		}
		num = myMessage.getQuantity();
		return num;
	}

	private void updateBadge(){

		int num = getUnreadMessage();

		if(num <= 0 ){
			if(badge.isShown()){
				badge.hide();
			}
		}else {
			badge.setText(num + "");
			if (!badge.isShown()) badge.show(true);
		}

	}

	// UI Handler --------------------------------------
	private static class MyHandler extends Handler{

		private WeakReference<MineActivity> mOuter;

		public MyHandler(MineActivity activity){
			mOuter = new WeakReference<MineActivity>(activity);
		}
		@Override
		public void handleMessage(Message msg) {

			super.handleMessage(msg);

			MineActivity outer = mOuter.get();

			if(outer != null ){
				switch (msg.what) {

				case 0:				
					outer.isLogin = true;
					UserBaseInfo user = PreferenceUtil.getUser(outer);
					outer.mToLoginHaedRelat.setVisibility(View.GONE);
					outer.mLoginHaedRelat.setVisibility(View.VISIBLE);
					if(null != user){
						outer.mUserNameText.setText(user.getUsername());	
					}
					outer.requestUserInfoAsync();
					outer.doGetMessageAsync();
					break;

				case 1:
					outer.isLogin = false;
					outer.mToLoginHaedRelat.setVisibility(View.VISIBLE);
					outer.mLoginHaedRelat.setVisibility(View.GONE);
					break;

				case 2:
					ImageLoader.getInstance().displayImage(outer.mUserInfo.getImage(), outer.mUserFaceImg);
					outer.mUserNameText.setText(outer.mUserInfo.getUsername());	
					outer.mUserBalanceText.setText("￥" + outer.mUserInfo.getBalance());
					break;

				case 3:
					outer.updateBadge();
					break;

				default:
					break;
				}
			}
		}
	}


	private void doGetMessageAsync() {
		new Thread(){
			public void run() {
				try {
					myMessage = WebClient.getInstance(MineActivity.this).getNoReadMessage();
				} catch (WebException e) {
					e.printStackTrace();
				}
				mHandler.sendEmptyMessage(3);
			};

		}.start();
	}

	private void requestUserInfoAsync() {

		new Thread(){
			public void run() {
				try {
					mUserInfo = WebClient.getInstance(MineActivity.this).getinfo();
					mHandler.sendEmptyMessage(2);
				} catch (WebException e) {
					Log.e(TAG, e.toString());
//					e.printStackTrace();
				}catch (Exception e) {
					
				}
			};
		}.start();
	};



	@Override
	protected void onTitleBarCreated(SimpleTitleBar titleBar) {
		super.onTitleBarCreated(titleBar);

		titleBar.setTitle(R.string.main_mine);

		titleBar.setRightButtonText(R.string.title_setting);
		titleBar.setOnRightButtonClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				ContextUtil.startActivity(MineActivity.this, SettingActivity.class);
			}
		});

	}

	//-------------------------------------------

	public class PopupWindows extends PopupWindow {

		@SuppressWarnings({ "deprecation" })
		public PopupWindows(Context mContext, View parent) {

			View view = View
					.inflate(mContext, R.layout.item_popupwindows, null);
			view.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.fade_ins));
			LinearLayout ll_popup = (LinearLayout) view
					.findViewById(R.id.ll_popup);
			ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.push_bottom_in_2));

			setWidth(LayoutParams.FILL_PARENT);
			setHeight(LayoutParams.FILL_PARENT);
			setBackgroundDrawable(new BitmapDrawable());
			setFocusable(true);
			setOutsideTouchable(true);
			setContentView(view);
			showAtLocation(parent, Gravity.BOTTOM, 0, 0);
			update();

			Button bt1 = (Button) view
					.findViewById(R.id.item_popupwindows_camera);
			Button bt2 = (Button) view
					.findViewById(R.id.item_popupwindows_Photo);
			Button bt3 = (Button) view
					.findViewById(R.id.item_popupwindows_cancel);
			bt1.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					photo();
					dismiss();
				}
			});
			bt2.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					Intent i = new Intent(
							Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
					//					i.setPackage("xxxx");// xxxx是具体报名，系统默认的一般是com.android.xx
					startActivityForResult(i, IMAGE_REQUEST_CODE);

					dismiss();
				}
			});
			bt3.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					dismiss();
				}
			});

		}
	}

	private String path = "";
	private Uri imageUri;

	public void photo() {
		Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		String state = Environment.getExternalStorageState();
		if (!state.equals(Environment.MEDIA_MOUNTED)) {
			App.showShortToast("没找到存储卡");
			return;
		}

		File file = new File(Environment.getExternalStorageDirectory()
				+"/hqhs/", String.valueOf(System.currentTimeMillis())
				+ ".jpg");
		path = file.getPath();
		App.showLog("path==="+path);
		imageUri = Uri.fromFile(file);
		openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
		startActivityForResult(openCameraIntent, CAMERA_REQUEST_CODE);
	}

	/**
	 * 图片压缩方法实现
	 * @param srcPath
	 * @returnc
	 */
	private Bitmap getimage(String srcPath) {
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		//开始读入图片，此时把options.inJustDecodeBounds 设回true了
		newOpts.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeFile(srcPath,newOpts);

		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		int hh = 800;//这里设置高度为800f
		int ww = 480;//这里设置宽度为480f
		//缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
		int be = 1;//be=1表示不缩放
		if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
			be = (int) (newOpts.outWidth / ww);
		} else if (w < h && h > hh) {//如果高度高的话根据高度固定大小缩放
			be = (int) (newOpts.outHeight / hh);
		}
		if (be <= 0)
			be = 1;
		newOpts.inSampleSize = be;//设置缩放比例
		//重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
		bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
		return compressImage(bitmap);//压缩好比例大小后再进行质量压缩
	}
	/**
	 * 质量压缩
	 * @param image
	 * @return
	 */
	private Bitmap compressImage(Bitmap image) {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
		int options = 100;
		while ( baos.toByteArray().length / 1024>100) {	//循环判断如果压缩后图片是否大于100kb,大于继续压缩		
			baos.reset(); //重置baos即清空baos
			options -= 10; //每次都减少10
			image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中

		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
		try {       
			FileOutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory()
					+  "/hqhs/faceImage.jpg");       
			bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
		} 
		catch (Exception e) {       

		}
		return bitmap;
	}


	/**
	 * 裁剪图片方法实现
	 * 
	 * @param uri
	 */
	public void startPhotoZoom(Uri uri) {

		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// 设置裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 100);
		intent.putExtra("outputY", 100);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, 2);
	}

	/**
	 * 保存裁剪之后的图片数据
	 * 
	 * @param picdata
	 */
	@SuppressWarnings("deprecation")
	private void getImageToView(Intent data) {
		Bundle extras = data.getExtras();
		if (extras != null) {
			Bitmap photo = extras.getParcelable("data");
			final Drawable drawable = new BitmapDrawable(photo);
			//显示图片
			//			mUserFaceImg.setImageDrawable(drawable);

			try {       
				FileOutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory()
						+  "/hqhs/faceImage.jpg");       
				photo.compress(Bitmap.CompressFormat.PNG, 90, out);
				//				showLoadingDialog("");
				FinalHttp fh = new FinalHttp();
				AjaxParams params = new AjaxParams();
				params.put("file", new File(Environment.getExternalStorageDirectory()+"/hqhs/faceImage.jpg"));
				fh.addHeader("X-Ticket", BaseActivity.getUUID(MineActivity.this));

				fh.post(Constants.IP+"/rest/member/image",params,new AjaxCallBack<Object>() {

					@Override
					public void onFailure(Throwable t, int errorNo,String strMsg) {
						super.onFailure(t, errorNo, strMsg);
						App.showLog("strMsg=="+strMsg);
					}

					@Override
					public void onSuccess(Object t) {
						super.onSuccess(t);
						App.showLog("t=="+t);
						mUserFaceImg.setImageDrawable(drawable);
					}


				});

			} 
			catch (Exception e) {       

			}
		}
	}
	/**  
	 * 取得图片回传的数据  
	 */  
	@SuppressWarnings({ "unused", "deprecation" })
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode != RESULT_CANCELED) {
			ContentResolver resolver = getContentResolver();
			Bitmap bm = null;
			switch (requestCode) {

			//本地图库
			case IMAGE_REQUEST_CODE:
				startPhotoZoom(data.getData());

				try {
					Uri originalUri = data.getData();
					bm = MediaStore.Images.Media.getBitmap(resolver, originalUri);
					String[] proj = {MediaStore.Images.Media.DATA};
					Cursor cursor = managedQuery(originalUri, proj, null, null, null);
					int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
					cursor.moveToFirst();
					String path = cursor.getString(column_index);
					//压缩大小
					getimage(path);

				} catch (Exception e) {
					Log.w(TAG, e.toString());
				}
				break;
			case CAMERA_REQUEST_CODE:

				if(EnviromentUtil.isSDExisted()){
					startPhotoZoom(imageUri);
					//压缩大小
					//getimage(Environment.getExternalStorageDirectory() + "/hqhs/faceImage.jpg");
					getimage(path);
				} else {
					App.showShortToast("没找到存储卡");
				}
				break;
			case RESULT_REQUEST_CODE:
				if (data != null) {
					getImageToView(data);
				}
				break;
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void initBadge() {
		badge = new BadgeView(this, mMessageText );
		badge.setBadgePosition(BadgeView.POSITION_BOTTOM_RIGHT);
		badge.setBadgeBackgroundColor(getResources().getColor(R.color.holo_title));
		badge.setTextColor(getResources().getColor(R.color.white));
	}

	@SuppressWarnings("unused")
	private void resetBadge(){		
		badge.setText("");
		badge.hide(); 
	}


}
